<?php
namespace Home\Controller;

use Wechat\Wechat;

/**
 * 微信入口
 */
class WechatController extends HomeController
{

    private $wechat; // 微信对象

    public function __construct()
    {
        parent::__construct();
        $token = 'zhibenjiaweixin'; //微信后台填写的TOKEN
        /* 加载微信SDK */
        try {
            $this->wechat = new Wechat($token);
        } catch (\Exception $e) {
            logs($e->getMessage());
            $this->wechat->response($e->getMessage());
        }
    }

    public function index()
    {
        /* 获取请求信息 */
        $data = $this->wechat->request();
        if ($data && is_array($data)) {
            switch($data['MsgType']){
                case Wechat::MSG_TYPE_EVENT:   // 事件
                    $response = $this->eventHandle($data['Event']);
                    $content = $response['content'];
                    $type = $response['type'];
                    $this->wechat->response($content, $type);   // 临时策略
                    break;
                case Wechat::MSG_TYPE_TEXT:
                    $content = '您的请求我们已收到, 请耐心等待...';
                    $type = Wechat::MSG_TYPE_TEXT;
                    $this->wechat->response($content, $type);   // 临时策略
                    break;
                default:
                    break;
            }
            /* 响应当前请求(自动回复) */
            //$this->wechat->response($content, $type);
        }else{
            $this->wechat->response('您的请求我们已收到, 请耐心等待...');
        }
    }

    /**
     * 事件处理
     */
    private function eventHandle($eventType){
        $response = array('content', 'type');   // 内容, 类型
        switch($eventType){
            case Wechat::MSG_EVENT_SUBSCRIBE:   // 关注事件
                $response['content'] = '加鑫财经, 欢迎您!';
                $response['type'] = Wechat::MSG_TYPE_TEXT;
                break;
            default:
                break;
        }
        return $response;
    }


}